import axios, { AxiosError } from "axios";
import i18n from "@/i18n";
import { Cookies } from "react-cookie";
import { API_WHITE_LIST } from "@/constants/list";
import type { ErrorResponse } from "@/types/response";
import { TOKEN } from "@/constants/cookies";

const cookies = new Cookies();

// 创建axios实例
export const api = axios.create({
  baseURL: "/api",
  timeout: 10000,
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加 Accept-Language 请求头
    const currentLanguage = i18n.language || "en-US";
    config.headers["Accept-Language"] = currentLanguage;

    // 检查当前请求URL是否在白名单中
    const requestUrl = config.url || "";
    const requestMethod = (config.method || "get").toLowerCase();
    console.log("requestUrl", requestUrl, "method", requestMethod);
    
    const isAuthWhitelisted = API_WHITE_LIST.some((whiteUrl) => {
      const [method, path] = whiteUrl.split(":");
      return method.toLowerCase() === requestMethod && requestUrl === path;
    });

    console.log("isAuthWhitelisted", isAuthWhitelisted);

    // 如果不在白名单中，从cookie获取token并添加到Authorization头
    if (!isAuthWhitelisted) {
      const token = cookies.get(TOKEN);
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`;
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    // 检查响应头是否包含token，如果包含则更新cookie
    // const token = response.headers["token"];
    // if (token) {
    //   // 移除可能的Bearer前缀
    //   cookies.set(TOKEN, token, { path: "/" });
    // }
    return response.data;
  },
  (error: AxiosError<ErrorResponse, unknown>) => {
    return Promise.reject(error);
  }
);
